﻿#region - 版 本 注 释 -
/*----------------------------------------------------------------
 * 版权所有 (c) 2024   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-GLJ2Q8J
 * 公司名称：
 * 命名空间：MessageBoxGuo
 * 唯一标识：3b617350-31ef-4d14-b07c-78290c7493b3
 * 文件名：MessageBoxGuo
 * 当前用户域：DESKTOP-GLJ2Q8J
 * 
 * 创建者：Guo-79991
 * 电子邮箱：799919859@qq.com
 * 创建时间：2025/7/15 11:53:52
 * 版本：V1.0.0
 *
 * 功能描述(Description):
 * 参考文档(Reference):
 * 数据表(Tables):
 * 作者(Author):Guo
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion - 版 本 注 释 -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace MessageBoxGuo
{
    public static class AlertBox
    {
        // 全局弹窗容器
        private static Canvas globalContainer;
        private static Window globalWindow;

        // 管理所有活动弹窗
        private static Dictionary<Panel, List<Border>> activeAlerts = new Dictionary<Panel, List<Border>>();

        // Win32 API 用于获取屏幕信息
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        static AlertBox()
        {
            InitializeGlobalContainer();
        }

        private static void InitializeGlobalContainer()
        {
            // 获取主屏幕的工作区域（排除任务栏）
            var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;

            // 创建全局窗口
            globalWindow = new Window
            {
                WindowStyle = WindowStyle.None,
                AllowsTransparency = true,
                Background = Brushes.Transparent,
                Topmost = true,
                ShowInTaskbar = false,
                Top = workingArea.Top + 20,
                Left = workingArea.Right - 320, // 300宽度 + 20边距
                Width = 300,
                Height = workingArea.Height - 40, // 留出上下边距
                WindowStartupLocation = WindowStartupLocation.Manual
            };

            // 创建全局容器
            globalContainer = new Canvas
            {
                Width = 300,
                VerticalAlignment = System.Windows.VerticalAlignment.Top,
                Margin = new Thickness(0, 0, 0, 0)
            };

            globalWindow.Content = globalContainer;
            globalWindow.Show();

            // 确保窗口不会获得焦点
            globalWindow.Focusable = false;
        }

        public static void Show(string message, AlertType type, Panel container, int duration = 3000, Brush customBackground = null, Brush customForeground = null)
        {
            if (!activeAlerts.ContainsKey(container))
            {
                activeAlerts[container] = new List<Border>();
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                CreateAlert(message, type, container, duration, customBackground, customForeground);
            });
        }

        public static void ShowGlobal(string message, AlertType type, int duration = 3000, Brush customBackground = null, Brush customForeground = null)
        {
            if (globalContainer == null) return;

            if (!activeAlerts.ContainsKey(globalContainer))
            {
                activeAlerts[globalContainer] = new List<Border>();
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                CreateAlert(message, type, globalContainer, duration, customBackground, customForeground);
            });
        }

        //private static void CreateAlert(string message, AlertType type, Panel container, int duration, Brush customBackground, Brush customForeground)
        //{
        //    //// 创建弹框边框
        //    //Border alertBorder = new Border
        //    //{
        //    //    CornerRadius = new CornerRadius(4),
        //    //    Padding = new Thickness(15, 10, 15, 10),
        //    //    Margin = new Thickness(0, 0, -10, 10),
        //    //    Effect = new System.Windows.Media.Effects.DropShadowEffect
        //    //    {
        //    //        BlurRadius = 10,
        //    //        Color = Colors.Gray,
        //    //        Opacity = 0.3,
        //    //        ShadowDepth = 2
        //    //    },
        //    //    Opacity = 0,
        //    //    RenderTransform = new TranslateTransform() // 用于动画
        //    //};

        //    // 创建弹框边框
        //    Border alertBorder = new Border
        //    {
        //        CornerRadius = new CornerRadius(4),
        //        Padding = new Thickness(15, 10, 15, 10),
        //        Margin = new Thickness(0, 0, 0, 10),
        //        Effect = new System.Windows.Media.Effects.DropShadowEffect
        //        {
        //            BlurRadius = 10,
        //            Color = Colors.Gray,
        //            Opacity = 0.3,
        //            ShadowDepth = 2
        //        },
        //        Opacity = 0,
        //        RenderTransform = new TranslateTransform(), // 用于动画
        //        HorizontalAlignment = HorizontalAlignment.Left,
        //        Width = 280 // 稍微减小宽度，确保边框完全可见
        //    };

        //    // 创建内容网格
        //    Grid contentGrid = new Grid();
        //    contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        //    contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        //    contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

        //    // 设置样式
        //    switch (type)
        //    {
        //        case AlertType.Success:
        //            alertBorder.Style = (Style)Application.Current.FindResource("SuccessAlertStyle");
        //            break;
        //        case AlertType.Error:
        //            alertBorder.Style = (Style)Application.Current.FindResource("ErrorAlertStyle");
        //            break;
        //        case AlertType.Warning:
        //            alertBorder.Style = (Style)Application.Current.FindResource("WarningAlertStyle");
        //            break;
        //        case AlertType.Info:
        //            alertBorder.Style = (Style)Application.Current.FindResource("InfoAlertStyle");
        //            break;
        //    }

        //    // 自定义背景和前景色
        //    if (customBackground != null)
        //        alertBorder.Background = customBackground;
        //    if (customForeground != null)
        //        alertBorder.BorderBrush = customForeground;

        //    // 创建图标
        //    TextBlock icon = new TextBlock
        //    {
        //        FontFamily = new FontFamily("Segoe UI Symbol"),
        //        FontSize = 16,
        //        VerticalAlignment = VerticalAlignment.Center,
        //        Margin = new Thickness(0, 0, 10, 0)
        //    };

        //    // 设置图标
        //    switch (type)
        //    {
        //        case AlertType.Success:
        //            icon.Text = "✔";
        //            icon.Foreground = Brushes.DarkGreen;
        //            break;
        //        case AlertType.Error:
        //            icon.Text = "✖";
        //            icon.Foreground = Brushes.DarkRed;
        //            break;
        //        case AlertType.Warning:
        //            icon.Text = "⚠";
        //            icon.Foreground = Brushes.OrangeRed;
        //            break;
        //        case AlertType.Info:
        //            icon.Text = "ℹ";
        //            icon.Foreground = Brushes.RoyalBlue;
        //            break;
        //    }

        //    // 自定义前景色
        //    if (customForeground != null)
        //        icon.Foreground = customForeground;

        //    // 创建消息文本
        //    TextBlock messageText = new TextBlock
        //    {
        //        Text = message,
        //        TextWrapping = TextWrapping.Wrap,
        //        VerticalAlignment = VerticalAlignment.Center,
        //        Foreground = customForeground ?? Brushes.DimGray
        //    };

        //    // 创建关闭按钮
        //    Button closeButton = new Button
        //    {
        //        Content = "×",
        //        FontSize = 16,
        //        Padding = new Thickness(5, 0, 5, 2),
        //        Margin = new Thickness(10, 0, 0, 0),
        //        Background = Brushes.Transparent,
        //        BorderThickness = new Thickness(0),
        //        Foreground = customForeground ?? Brushes.Gray,
        //        Cursor = System.Windows.Input.Cursors.Hand
        //    };

        //    // 添加元素到网格
        //    Grid.SetColumn(icon, 0);
        //    Grid.SetColumn(messageText, 1);
        //    Grid.SetColumn(closeButton, 2);
        //    contentGrid.Children.Add(icon);
        //    contentGrid.Children.Add(messageText);
        //    contentGrid.Children.Add(closeButton);

        //    // 将网格添加到边框
        //    alertBorder.Child = contentGrid;

        //    // 添加到容器
        //    container.Children.Add(alertBorder);

        //    // 添加到活动弹窗列表
        //    activeAlerts[container].Add(alertBorder);

        //    // 设置关闭按钮事件
        //    closeButton.Click += (s, e) =>
        //    {
        //        RemoveAlert(alertBorder, container);
        //    };

        //    // 动画显示
        //    DoubleAnimation showAnimation = new DoubleAnimation
        //    {
        //        From = 0,
        //        To = 1,
        //        Duration = TimeSpan.FromMilliseconds(300)
        //    };

        //    // 从右侧滑入动画
        //    DoubleAnimation slideInAnimation = new DoubleAnimation
        //    {
        //        From = 100,
        //        To = 0,
        //        Duration = TimeSpan.FromMilliseconds(300)
        //    };

        //    alertBorder.BeginAnimation(UIElement.OpacityProperty, showAnimation);
        //    alertBorder.RenderTransform.BeginAnimation(TranslateTransform.XProperty, slideInAnimation);

        //    // 更新所有弹窗位置
        //    UpdateAlertPositions(container);

        //    // 设置自动关闭计时器
        //    DispatcherTimer closeTimer = new DispatcherTimer
        //    {
        //        Interval = TimeSpan.FromMilliseconds(duration)
        //    };
        //    closeTimer.Tick += (s, e) =>
        //    {
        //        closeTimer.Stop();
        //        RemoveAlert(alertBorder, container);
        //    };
        //    closeTimer.Start();
        //}






        private static void CreateAlert(string message, AlertType type, Panel container, int duration, Brush customBackground, Brush customForeground)
        {
            // 创建弹框边框
            Border alertBorder = new Border
            {
                CornerRadius = new CornerRadius(4),
                Padding = new Thickness(15, 10, 15, 10),
                Margin = new Thickness(0, 0, 0, 10),
                Effect = new System.Windows.Media.Effects.DropShadowEffect
                {
                    BlurRadius = 10,
                    Color = Colors.Gray,
                    Opacity = 0.3,
                    ShadowDepth = 2
                },
                Opacity = 0,
                RenderTransform = new TranslateTransform(), // 用于动画
                HorizontalAlignment = HorizontalAlignment.Left,
                Width = 280 // 稍微减小宽度，确保边框完全可见
            };

            // 根据类型设置样式（不再使用资源查找）
            switch (type)
            {
                case AlertType.Success:
                    alertBorder.Background = new SolidColorBrush(Color.FromRgb(240, 249, 235));
                    alertBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(194, 231, 176));
                    break;
                case AlertType.Error:
                    alertBorder.Background = new SolidColorBrush(Color.FromRgb(254, 240, 240));
                    alertBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(251, 196, 196));
                    break;
                case AlertType.Warning:
                    alertBorder.Background = new SolidColorBrush(Color.FromRgb(253, 246, 236));
                    alertBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(245, 218, 177));
                    break;
                case AlertType.Info:
                    alertBorder.Background = new SolidColorBrush(Color.FromRgb(237, 242, 252));
                    alertBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(186, 200, 243));
                    break;
            }

            // 自定义背景和前景色（覆盖默认样式）
            if (customBackground != null)
                alertBorder.Background = customBackground;
            if (customForeground != null)
                alertBorder.BorderBrush = customForeground;

            // 创建内容网格
            Grid contentGrid = new Grid();
            contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            contentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

            // 创建图标
            TextBlock icon = new TextBlock
            {
                FontFamily = new FontFamily("Segoe UI Symbol"),
                FontSize = 16,
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 10, 0)
            };

            // 设置图标和颜色
            switch (type)
            {
                case AlertType.Success:
                    icon.Text = "✔";
                    icon.Foreground = customForeground ?? new SolidColorBrush(Color.FromRgb(82, 196, 26));
                    break;
                case AlertType.Error:
                    icon.Text = "✖";
                    icon.Foreground = customForeground ?? new SolidColorBrush(Color.FromRgb(245, 108, 108));
                    break;
                case AlertType.Warning:
                    icon.Text = "⚠";
                    icon.Foreground = customForeground ?? new SolidColorBrush(Color.FromRgb(230, 162, 60));
                    break;
                case AlertType.Info:
                    icon.Text = "ℹ";
                    icon.Foreground = customForeground ?? new SolidColorBrush(Color.FromRgb(144, 147, 153));
                    break;
            }

            // 创建消息文本
            TextBlock messageText = new TextBlock
            {
                Text = message,
                TextWrapping = TextWrapping.Wrap,
                VerticalAlignment = VerticalAlignment.Center,
                Foreground = customForeground ?? new SolidColorBrush(Color.FromRgb(96, 98, 102))
            };

            // 创建关闭按钮
            Button closeButton = new Button
            {
                Content = "×",
                FontSize = 16,
                Padding = new Thickness(5, 0, 5, 2),
                Margin = new Thickness(10, 0, 0, 0),
                Background = Brushes.Transparent,
                BorderThickness = new Thickness(0),
                Foreground = customForeground ?? new SolidColorBrush(Color.FromRgb(144, 147, 153)),
                Cursor = System.Windows.Input.Cursors.Hand
            };

            // 添加元素到网格
            Grid.SetColumn(icon, 0);
            Grid.SetColumn(messageText, 1);
            Grid.SetColumn(closeButton, 2);
            contentGrid.Children.Add(icon);
            contentGrid.Children.Add(messageText);
            contentGrid.Children.Add(closeButton);

            // 将网格添加到边框
            alertBorder.Child = contentGrid;

            // 添加到容器
            container.Children.Add(alertBorder);

            // 添加到活动弹窗列表
            activeAlerts[container].Add(alertBorder);

            // 设置关闭按钮事件
            closeButton.Click += (s, e) =>
            {
                RemoveAlert(alertBorder, container);
            };

            // 动画显示
            DoubleAnimation showAnimation = new DoubleAnimation
            {
                From = 0,
                To = 1,
                Duration = TimeSpan.FromMilliseconds(300)
            };

            // 从右侧滑入动画
            DoubleAnimation slideInAnimation = new DoubleAnimation
            {
                From = 100,
                To = 0,
                Duration = TimeSpan.FromMilliseconds(300)
            };

            alertBorder.BeginAnimation(UIElement.OpacityProperty, showAnimation);
            alertBorder.RenderTransform.BeginAnimation(TranslateTransform.XProperty, slideInAnimation);

            // 更新所有弹窗位置
            UpdateAlertPositions(container);

            // 设置自动关闭计时器
            DispatcherTimer closeTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(duration)
            };
            closeTimer.Tick += (s, e) =>
            {
                closeTimer.Stop();
                RemoveAlert(alertBorder, container);
            };
            closeTimer.Start();
        }

        private static void RemoveAlert(Border alert, Panel container)
        {
            if (!activeAlerts.ContainsKey(container) || !activeAlerts[container].Contains(alert))
                return;

            // 动画隐藏
            DoubleAnimation hideAnimation = new DoubleAnimation
            {
                From = 1,
                To = 0,
                Duration = TimeSpan.FromMilliseconds(300)
            };

            // 向右侧滑出动画
            DoubleAnimation slideOutAnimation = new DoubleAnimation
            {
                From = 0,
                To = 100,
                Duration = TimeSpan.FromMilliseconds(300)
            };

            hideAnimation.Completed += (s, e) =>
            {
                container.Children.Remove(alert);
                activeAlerts[container].Remove(alert);

                // 更新剩余弹窗位置
                UpdateAlertPositions(container);
            };

            alert.BeginAnimation(UIElement.OpacityProperty, hideAnimation);
            alert.RenderTransform.BeginAnimation(TranslateTransform.XProperty, slideOutAnimation);
        }

        private static void UpdateAlertPositions(Panel container)
        {
            if (!activeAlerts.ContainsKey(container))
                return;

            double currentTop = 0;

            foreach (var alert in activeAlerts[container])
            {
                // 确保UI元素已渲染，获取实际高度
                if (alert.ActualHeight == 0 && alert.IsMeasureValid == false)
                {
                    alert.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                    alert.Arrange(new Rect(0, 0, alert.DesiredSize.Width, alert.DesiredSize.Height));
                }

                double alertHeight = alert.ActualHeight > 0 ? alert.ActualHeight : 60; // 默认高度

                // 设置弹窗位置
                if (container is Canvas canvas)
                {
                    Canvas.SetTop(alert, currentTop);
                    Canvas.SetLeft(alert, 0);
                }

                // 计算下一个弹窗的位置
                currentTop += alertHeight + alert.Margin.Top + alert.Margin.Bottom;
            }

            // 对于全局窗口，确保高度足够
            if (container == globalContainer && globalWindow != null)
            {
                var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
                globalWindow.Height = Math.Min(currentTop + 40, workingArea.Height - 40);
            }
        }
    }
}
